package cn.stylefeng.guns.modular.robot.service.impl;

import cn.stylefeng.guns.core.common.page.LayuiPageFactory;
import cn.stylefeng.guns.core.common.page.LayuiPageInfo;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.modular.robot.entity.Group;
import cn.stylefeng.guns.modular.robot.entity.Order;
import cn.stylefeng.guns.modular.robot.entity.OrderBatch;
import cn.stylefeng.guns.modular.robot.entity.enums.GroupMode;
import cn.stylefeng.guns.modular.robot.entity.vo.resp.BatchInfo;
import cn.stylefeng.guns.modular.robot.entity.vo.resp.BatchInfoResp;
import cn.stylefeng.guns.modular.robot.mapper.OrderMapper;
import cn.stylefeng.guns.modular.robot.service.GroupService;
import cn.stylefeng.guns.modular.robot.service.OrderBatchService;
import cn.stylefeng.guns.modular.robot.service.OrderService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private GroupService groupService;
    @Resource
    private OrderBatchService orderBatchService;

    @Override
    public LayuiPageInfo list(String customId, String groupId, String groupName, Long pageSize, Long pageNum) {
        String account = ShiroKit.getUser().getAccount();
        IPage<Order> groupIPage = lambdaQuery()
                .eq(!"admin".equals(account), Order::getCustomName, account)
                .eq(StringUtils.isNotBlank(customId), Order::getCustomId, customId)
                .like(StringUtils.isNotEmpty(groupId), Order::getGroupId, groupId)
                .like(StringUtils.isNotEmpty(groupName), Order::getGroupName, groupName)
                .orderByDesc(Order::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
        return LayuiPageFactory.createPageInfo(groupIPage);
    }

    @Override
    public LayuiPageInfo listByBatch(String batchId, Long pageSize, Long pageNum) {
        IPage<Order> groupIPage = lambdaQuery()
                .eq(Order::getBatchId, batchId)
                .orderByDesc(Order::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
        return LayuiPageFactory.createPageInfo(groupIPage);
    }

    @Override
    public ResponseData summary(String batchId) {
        if (StringUtils.isBlank(batchId)) {
            return ResponseData.success();
        }
        List<Order> orders = lambdaQuery()
                .eq(Order::getBatchId, batchId)
                .list();
        if (CollectionUtils.isEmpty(orders)) {
            return ResponseData.success();
        }
        List<OrderBatch> orderBatches = orderBatchService.lambdaQuery()
                .eq(OrderBatch::getBatchId, batchId)
                .list();
        if (CollectionUtils.isEmpty(orderBatches)) {
            return ResponseData.success();
        }
        OrderBatch orderBatch = orderBatches.get(0);
        BigDecimal sumInAmount = BigDecimal.ZERO;
        BigDecimal needGive = BigDecimal.ZERO;
        BigDecimal sumOutAmount = BigDecimal.ZERO;
        int inCount = 0;
        int outCount = 0;
        for (Order order : orders) {
            if ("入款".equals(order.getType())) {
                inCount++;
                if (Objects.isNull(order.getExtract())) {
                    order.setExtract(BigDecimal.ZERO);
                }
                sumInAmount = sumInAmount.add(order.getAmount());
                if (order.getExchangeRate().compareTo(BigDecimal.ZERO) == 0) {
                    order.setExchangeRate(BigDecimal.valueOf(1));
                }
                needGive = needGive.add(order.getAmount().subtract(order.getExtract()).subtract(order.getAmount().subtract(order.getExtract())
                        .multiply(order.getRate())).divide(order.getExchangeRate(), 4, RoundingMode.HALF_UP));
            }
            if ("下发".equals(order.getType())) {
                outCount++;
                if (order.getExchangeRate().compareTo(BigDecimal.ZERO) == 0) {
                    order.setExchangeRate(BigDecimal.valueOf(1));
                }
                sumOutAmount = sumOutAmount.add(order.getAmount().divide(order.getExchangeRate(), 4, RoundingMode.HALF_UP));
            }
        }
        BatchInfoResp batchInfo = new BatchInfoResp();
        batchInfo.setSumInAmount(sumInAmount);
        batchInfo.setInCount(inCount);
        batchInfo.setSumOutAmount(sumOutAmount);
        batchInfo.setOutCount(outCount);
        batchInfo.setNeedGive(needGive);
        batchInfo.setResidue(needGive.subtract(sumOutAmount));
        batchInfo.setStatus(Objects.isNull(orderBatch.getEndTime()) ? "进行中" : "已完成");
        String endTime = Objects.isNull(orderBatch.getEndTime()) ? "未结束" : DateFormatUtils.format(orderBatch.getEndTime(), "yyyy-MM-dd HH:mm:ss");
        batchInfo.setTime(DateFormatUtils.format(orderBatch.getStartTime(), "yyyy-MM-dd HH:mm:ss") + "----" + endTime);
        batchInfo.setModel(GroupMode.USDT.equals(orderBatch.getGroupMode()) ? "U本位账单" : "币本位账单");
        return ResponseData.success(batchInfo);
    }
}
